/**
 * 简化的API工具类 - JavaScript版本
 * 用于兼容.js文件的引用
 */

const config = require('../config/config.js');
const BASE_URL = config.BASE_URL || 'http://192.168.137.1:8090';

/**
 * 获取存储的Token
 */
function getToken() {
  try {
    return wx.getStorageSync('token') || wx.getStorageSync('access_token');
  } catch (error) {
    console.warn('获取Token失败:', error);
    return null;
  }
}

/**
 * 统一的HTTP请求方法
 */
function request(options) {
  const {
    url,
    method = 'GET',
    data,
    skipAuth = false,
    showLoading = false,
    loadingText = '加载中...'
  } = options;

  // 生成请求ID用于日志追踪
  const requestId = Math.random().toString(36).substr(2, 9);
  const startTime = Date.now();

  // 显示loading
  if (showLoading) {
    wx.showLoading({ title: loadingText });
  }

  return new Promise((resolve, reject) => {
    // 构建完整URL
    const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`;
    
    // 构建请求头
    const headers = {
      'Content-Type': 'application/json'
    };
    
    // 添加Token
    if (!skipAuth) {
      const token = getToken();
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
    }

    // 记录请求开始日志
    console.log(`[HTTP-${requestId}] 🚀 发起请求:`, {
      url: fullUrl,
      method,
      headers,
      data,
      timestamp: new Date().toISOString()
    });

    // 发起请求
    wx.request({
      url: fullUrl,
      method,
      data,
      header: headers,
      timeout: 15000,
      success: (response) => {
        const duration = Date.now() - startTime;

        // 记录响应成功日志
        console.log(`[HTTP-${requestId}] ✅ 请求成功:`, {
          statusCode: response.statusCode,
          duration: `${duration}ms`,
          responseData: response.data,
          timestamp: new Date().toISOString()
        });

        // 隐藏loading
        if (showLoading) {
          wx.hideLoading();
        }

        // 检查HTTP状态码
        if (response.statusCode >= 200 && response.statusCode < 300) {
          // 检查业务状态码
          const data = response.data;
          if (data && data.code) {
            // 如果是RestApiResponse格式，检查业务状态码
            if (data.code === "200" || data.code === 200) {
              // 业务成功
              resolve(response);
            } else {
              // 业务失败
              const error = new Error(data.message || `业务错误: ${data.code}`);
              error.response = response;
              error.businessCode = data.code;
              reject(error);
            }
          } else if (data && typeof data.code === 'number') {
            // 如果是CommonResult格式，检查数字状态码
            if (data.code === 200) {
              // 业务成功
              resolve(response);
            } else {
              // 业务失败
              const error = new Error(data.message || `业务错误: ${data.code}`);
              error.response = response;
              error.businessCode = data.code;
              reject(error);
            }
          } else {
            // 没有业务状态码，直接返回
            resolve(response);
          }
        } else {
          const error = new Error(`HTTP ${response.statusCode}`);
          error.response = response;
          reject(error);
        }
      },
      fail: (error) => {
        const duration = Date.now() - startTime;

        // 记录请求失败日志
        console.log(`[HTTP-${requestId}] ❌ 请求失败:`, {
          error,
          statusCode: error.statusCode,
          duration: `${duration}ms`,
          timestamp: new Date().toISOString()
        });

        // 隐藏loading
        if (showLoading) {
          wx.hideLoading();
        }

        reject(error);
      }
    });
  });
}

/**
 * GET请求
 */
function get(url, data, options = {}) {
  return request({
    url,
    method: 'GET',
    data,
    ...options
  });
}

/**
 * POST请求
 */
function post(url, data, options = {}) {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  });
}

/**
 * PUT请求
 */
function put(url, data, options = {}) {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  });
}

/**
 * DELETE请求
 */
function   deleteRequest(url, data, options = {}) {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  });
}

/**
 * 发送测试消息
 */
function sendTestMessage(userId) {
  return request({
    url: `/api/wechat/subscribe/test?userId=${userId}`,
    method: 'POST',
    showLoading: true,
    loadingText: '发送消息中...'
  });
}

/**
 * 发送饮水提醒消息
 */
function sendWaterReminder(userId, currentAmount, goalAmount, time) {
  // 使用当前时间确保立即发送
  const currentTime = new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
  
  return request({
    url: `/api/wechat/subscribe/water-reminder?userId=${userId}&waterAmount=${currentAmount}&goalAmount=${goalAmount}&reminderTime=${encodeURIComponent(currentTime)}`,
    method: 'POST',
    showLoading: true,
    loadingText: '发送提醒中...'
  });
}

/**
 * 发送目标达成消息
 */
function sendGoalAchieved(userId, goalAmount, actualAmount, date) {
  // 使用当前日期确保立即发送
  const currentDate = new Date().toLocaleDateString('zh-CN');
  
  return request({
    url: `/api/wechat/subscribe/goal-achieved?userId=${userId}&goalAmount=${goalAmount}&actualAmount=${actualAmount}&achieveDate=${encodeURIComponent(currentDate)}`,
    method: 'POST',
    showLoading: true,
    loadingText: '发送通知中...'
  });
}

// 用户相关API
const userApi = {
  // 获取用户信息（包括微信绑定状态）
  getUserInfo: (userId) => {
    return request({
      url: `/user/${userId}`,
      method: 'GET'
    });
  },
  
  // 更新用户信息
  updateUserInfo: (userId, data) => {
    return request({
      url: `/user/${userId}`,
      method: 'PUT',
      data
    });
  }
};

// 微信相关API
const wechatApi = {
  // 绑定微信账号
  bindWechat: (userId, code) => {
    return request({
      url: '/wechat/bind',
      method: 'POST',
      data: {
        userId,
        code
      }
    });
  },
  
  // 解绑微信账号
  unbindWechat: (userId) => {
    return request({
      url: '/wechat/unbind',
      method: 'POST',
      data: {
        userId
      }
    });
  }
};

module.exports = {
  request,
  sendTestMessage,
  sendWaterReminder,
  sendGoalAchieved,
  userApi,
  wechatApi
}; 